//
//  PersonPageViewController.m
//  SchoolTimetable
//
//  Created by 梦里都是梦 on 16/1/6.
//  Copyright (c) 2016年 Yuanlinqian. All rights reserved.
//

#import "PersonPageViewController.h"
#import "LoginPageViewController.h"
#import "MyImageView.h"
#import <BmobSDK/BmobProFile.h>
#import "MyButton.h"
#import "RootTabBarController.h"
#import "UserInfoPageViewController.h"

typedef NS_ENUM(NSInteger,ChosePhotoType){
    ChosePhotoTypeAlbum,
    ChosePhotoTypeCamera
};
@interface PersonPageViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet MyImageView *userIconImgView;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet MyButton *userMessageBtn;
@property (weak, nonatomic) IBOutlet MyButton *userInfoBtn;
@property (weak, nonatomic) IBOutlet MyButton *clearCache;
@property (weak, nonatomic) IBOutlet MyButton *logoutBtn;

@end

@implementation PersonPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self userRefreshUserInfo:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(userRefreshUserInfo:) name:USER_REFRESH_USERINFO object:nil];

}
-(void)userRefreshUserInfo:(NSNotification *)notice
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser) {
        NSString * userNickName = [bUser objectForKey:@"userNickName"];
        if (userNickName.length == 0) {
            self.userNameLabel.text = bUser.username;
        }
        else
        {
            self.userNameLabel.text = userNickName;
        }
        NSString * urlStr = [bUser objectForKey:@"userIconUrl"];
        [self.userIconImgView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"ic_normal_avatar"] ];
    }else{
        //对象为空时，可打开用户注册界面
        self.userNameLabel.text = @"点击头像登陆";
        self.userIconImgView.image = [UIImage imageNamed:@"ic_normal_avatar"];
    }
    
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:USER_REFRESH_USERINFO];
    [[NSNotificationCenter defaultCenter] removeObserver:SAVE_MESSAGE];
    [[NSNotificationCenter defaultCenter] removeObserver:SYN_MESSAGE];
}

- (IBAction)userIconTap:(UITapGestureRecognizer *)sender {
    
    if ([BmobUser getCurrentUser]) {
        [self userIconChosePic];
    }
    else{
        [self presentToLoginViewController];
    }
}
- (IBAction)userInfoBtnPressed:(MyButton *)sender {
    
    if ([BmobUser getCurrentUser])
    {
         UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UserInfoPageViewController * UIPVc = [storyBoard instantiateViewControllerWithIdentifier:@"UserInfoPageViewController"];
        [self.navigationController pushViewController:UIPVc animated:YES];
    }
    else
    {
        [SVProgressHUD showInfoWithStatus:@"请先登陆"];
    }
}
- (IBAction)userInfoMessageBtnPressed:(MyButton *)sender {
    if ([BmobUser getCurrentUser]) {
        UIAlertController *  alert = [UIAlertController  alertControllerWithTitle:@"提示" message:@"如果同步信息现有课表将会覆盖,是否同步?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction * syn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSNotificationCenter defaultCenter]postNotificationName:SYN_MESSAGE object:nil];
        }];
        [alert addAction:cancel];
        [alert addAction:syn];
        [self presentViewController:alert animated:YES completion:^{
        }];
        
    }
    else
    {
        [SVProgressHUD showInfoWithStatus:@"请先登陆"];
    }


    
    
}
// 清理缓存
- (IBAction)clearCacheBtnPressed:(MyButton *)sender {
    
    // 获取缓存文件个数
    NSUInteger diskCount = [[SDImageCache sharedImageCache] getDiskCount];
    // 获取缓存的大小
    NSUInteger cacheSize = [[SDImageCache sharedImageCache]getSize];
    NSString * msg = [NSString stringWithFormat:@"缓存文件数量:%lu 缓存文件大小:%luB",diskCount,cacheSize];
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"清除缓存" message:msg preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * cancal = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [alertController addAction:cancal];
    UIAlertAction * clearAction = [UIAlertAction actionWithTitle:@"清除缓存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//        [SVProgressHUD showProgress:1];
        NSString*directory=NSHomeDirectory();
        NSLog(@"directory:%@",directory);
        [[SDImageCache sharedImageCache] clearMemory];
        [[SDImageCache sharedImageCache] cleanDisk];
        NSLog(@"%lu",cacheSize);
    }];
    [alertController addAction:clearAction];
    [self.navigationController presentViewController:alertController animated:YES completion:nil];

}
// 退出登陆
- (IBAction)logoutBtnPressed:(MyButton *)sender {
    if ([BmobUser getCurrentUser]) {
        UIAlertController *  alert = [UIAlertController  alertControllerWithTitle:@"提示" message:@"是否退出登陆?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction * quit = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [BmobUser logout];
            [[NSNotificationCenter defaultCenter]postNotificationName:USER_REFRESH_USERINFO object:nil];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:cancel];
        [alert addAction:quit];
        [self presentViewController:alert animated:YES completion:^{
        }];

    }
    else
    {
        [SVProgressHUD showInfoWithStatus:@"请先登陆"];
    }
}
// 换头像点击事件
- (void)userIconChosePic {
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"选择相片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * album = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chosePhoto:ChosePhotoTypeAlbum];
    }];
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chosePhoto:ChosePhotoTypeCamera];
    }];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:album];
    [alert addAction:camera];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
}
-(void)chosePhoto:(ChosePhotoType)type
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    if (type == ChosePhotoTypeAlbum) {
        
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
    }
    else if (type == ChosePhotoTypeCamera)
    {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"相机不可用"];
            return;
        }
        
    }
    [self presentViewController:picker animated:YES completion:^{
        
    }];
    
}

-(void)presentToLoginViewController
{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginPageViewController * loginVc = [storyBoard instantiateViewControllerWithIdentifier:@"LoginPageViewController"];
    [self.navigationController pushViewController:loginVc animated:YES];
    RootTabBarController * rootTabBarController =  (RootTabBarController *)[self.navigationController parentViewController];
    rootTabBarController.ownTabBar.hidden = YES;
    loginVc.htblock = ^{
        RootTabBarController * rootTabBarController =  (RootTabBarController *)[self.navigationController parentViewController];
        rootTabBarController.ownTabBar.hidden = NO;
        
    };
}
#pragma mark - 选择图片的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * img = info[UIImagePickerControllerEditedImage];
    
    NSData * imgData = nil;
    NSString * docmentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString * imgDirPath = [docmentPath stringByAppendingString:@"/ImageFile"];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    // 判断沙盒是否存在文件夹
    if ([fileManager fileExistsAtPath:imgDirPath]) {
        
    }
    else{
        // 创建文件夹
        [[NSFileManager defaultManager] createDirectoryAtPath:imgDirPath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    NSString * imgPath = [imgDirPath stringByAppendingString:@"userIcon"];
    NSData * saveImgData = UIImagePNGRepresentation(img);
    // 将数据写入沙盒
    bool isSuc = [saveImgData writeToFile:imgPath atomically:YES];
    if (isSuc) {
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }
    
    if (UIImagePNGRepresentation(img)) {
        imgData = UIImagePNGRepresentation(img);
    }
    else if (UIImageJPEGRepresentation(img, 0.1)){
        // 压缩处理
        imgData = UIImageJPEGRepresentation(img, 0.1);
    }
    UIImage * theImg = [self zioImageWithData:imgData limitedWith:140];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        [self uploadImageWithImage:theImg];
    }];
}
-(UIImage *)zioImageWithData:(NSData *)imgData limitedWith:(CGFloat)width
{
    // 获取图片
    UIImage * img = [UIImage imageWithData:imgData];
    
    CGSize oldImgSize = img.size;
    
    if (width > oldImgSize.width) {
        width = oldImgSize.width;
    }
    CGFloat newHeight = oldImgSize.height * ((CGFloat)width/oldImgSize.width);
    
    // 创建新的图片的大小
    CGSize size = CGSizeMake(width, newHeight);
    
    // 开启一个图片句柄
    UIGraphicsBeginImageContext(size);
    
    // 将图片画入新的size里面
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从图片句柄中获取一张新的图片
    UIImage * newImg = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关闭图片句柄
    UIGraphicsEndImageContext();
    
    return  newImg;
}
// 上传图片到Bmob服务器
-(void)uploadImageWithImage:(UIImage *)img
{
    [SVProgressHUD showWithStatus:@"上传图片"];
    
    NSData *imgData = UIImagePNGRepresentation(img);
    
    [BmobProFile uploadFileWithFilename:@"用户图标" fileData:imgData block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
        if (isSuccessful) {
            
            // 将上传的图片链接和用户联系起来
            BmobUser * user = [BmobUser getCurrentUser];
            [user setObject:file.url forKey:@"userIconUrl"];
            [user updateInBackgroundWithResultBlock:^(BOOL isSuc, NSError *err) {
                if(isSuc){
                    [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                    [self.userIconImgView sd_setImageWithURL:[NSURL URLWithString:file.url]];
//                    [[NSNotificationCenter defaultCenter]postNotificationName:USER_REFRESH_USERINFO object:nil];
                }
                else{
                    [SVProgressHUD showErrorWithStatus:[err localizedDescription]];
                }
            }];
            
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        }
    } progress:^(CGFloat progress) {
        //上传进度
        [SVProgressHUD showProgress:progress];
    }];
    
}
#pragma mark - UITableViewDelegate/DataSource




// 跳转到登陆页面的方法
-(void)loginClicked:(UIButton *)sender
{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginPageViewController * loginVc = [storyBoard instantiateViewControllerWithIdentifier:@"LoginPageViewController"];
    [self.navigationController presentViewController:[[UINavigationController alloc]initWithRootViewController:loginVc] animated:YES completion:nil];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
